/**
 * @author hieu
 */
var dashboard = {
	_store : {
		variable : {
			timeout_alert : null,
		},
	},
	_all_popup : {},
	_show_popup : {},
}

dashboard.is_arr = function(arr) { return (arr != null && arr.constructor == Array) };

dashboard.is_str = function(str) { return (str && (/string/).test(typeof str)) };

dashboard.is_func = function(func) { return (func != null && func.constructor == Function) };

dashboard.is_num = function(num) { var num = Number(num); return (num != null && !isNaN(num)) };

dashboard.is_int = function (x) {var y=parseInt(x);if (isNaN(y)) return false;return x==y && x.toString()==y.toString();} 

dashboard.is_obj = function(obj) { return (obj != null && obj instanceof Object) };

dashboard.is_exists = function(obj) { return (obj != null && obj != undefined && obj != "undefined") };

dashboard.is_blank = function(str) { return (dashboard.util_trim(str) == "") };

dashboard.is_email = function(str) {return (/^[a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i).test(dashboard.util_trim(str))};

dashboard.is_username = function(value){ return (value.match(/^[0-9]/) == null) && (value.search(/^[0-9_a-zA-Z]*$/) > -1); }

dashboard.is_link = function(str){ return (/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/).test(dashboard.util_trim(str)) };

dashboard.is_image = function(imagePath){
  var fileType = imagePath.substring(imagePath.lastIndexOf("."),imagePath.length).toLowerCase();
  return (fileType == ".gif") || (fileType == ".jpg") || (fileType == ".png") || (fileType == ".jpeg");
};

dashboard.is_ff  = function(){ return (/Firefox/).test(navigator.userAgent) };

dashboard.is_ie  = function() { return (/MSIE/).test(navigator.userAgent) };

dashboard.is_ie6 = function() { return (/MSIE 6/).test(navigator.userAgent) };

dashboard.is_ie7 = function() { return (/MSIE 7/).test(navigator.userAgent) };

dashboard.is_ie8 = function() { return (/MSIE 8/).test(navigator.userAgent) };

dashboard.is_chrome = function(){ return (/Chrome/).test(navigator.userAgent) };

dashboard.is_opera = function() { return (/Opera/).test(navigator.userAgent) };

dashboard.is_safari = function(){ return (/Safari/).test(navigator.userAgent) };

dashboard.redirect = function(url){window.location = url};
dashboard.join = function(str) {
	var store = [str];
	return function extend(other) {
		if (other != null && 'string' == typeof other){
			store.push(other);
			return extend;
		}	
		return store.join('');
	}
};
/**
 * 
 */
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
}
/**
 * Utils
 */
dashboard.util_trim = function(str) {return (/string/).test(typeof str) ? str.replace(/^\s+|\s+$/g, "") : ""};

dashboard.util_random = function(a, b) { return Math.floor(Math.random() * (b - a + 1)) + a };

dashboard.get_ele = function(id) { return document.getElementById(id) };
dashboard.util_isValidCode = function(txt){
	var invalidCode = "`~!@#$%^&*()-_=+\\|[{]};:'\",<.>/?";
	for (var i = 0; i < invalidCode.length; i++) {
	    for (var j = 0; j < txt.length; j++) {
	        if (txt.charAt(j) == invalidCode.charAt(i)) {
	            return false;
	        }
	    }
	}
	return true;
}
dashboard.util_isValidCode_lite = function(txt){
	var invalidCode = "'\"";
	for (var i = 0; i < invalidCode.length; i++) {
	    for (var j = 0; j < txt.length; j++) {
	        if (txt.charAt(j) == invalidCode.charAt(i)) {
	            return false;
	        }
	    }
	}
	return true;
}

dashboard.util_isValidCodeForName = function (txt) {
	var invalidCode = "`~!@#$%^&*()-_=+\\|[{]};:\",<.>/?";
	for (var i = 0; i < invalidCode.length; i++) {
	    for (var j = 0; j < txt.length; j++) {
	        if (txt.charAt(j) == invalidCode.charAt(i)) {
	            return false;
	        }
	    }
	}
	return true;
}
dashboard.util_containsNumber = function (txt) {
	var seriesNumber = "0123456789";
	for (var i = 0; i < seriesNumber.length; i++) {
	    for (var j = 0; j < txt.length; j++) {
	        if (txt.charAt(j) == seriesNumber.charAt(i)) {
	            return true;
	        }
	    }
	}
	return false;
}
dashboard.cookie = {
	clearAllCookies : function () {
		var cookies = document.cookie.split(";");
		var ck = "";
		for(var i = 0; i < cookies.length; i++) {
			ck = jQuery.trim(cookies[i]).split("=")[0]; //get cookie name
		    if ((ck.substr(0, 3) == config_variable.cookie.prefix) && (ck != config_variable.cookie.remember_me) && (ck != config_variable.cookie.username_login)) {
		        jQuery.cookie(ck, null, { path: '/' });
		    }
		}
	},
}
/**
 * 
 * @param {Object} str
 * Need <div id="alert"></div> 
 */

dashboard.show_alert = function(str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	$('#alert').html('').append(content);
	dashboard._store.variable.timeout_alert = setTimeout('dashboard.time_out_close_alert()', 3000);
};
dashboard.show_alert_fix = function(id,str) {
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);	
};
dashboard.show_alert_fix_time = function(id,str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);	
	dashboard._store.variable.timeout_alert = setTimeout('dashboard.time_out_close_alert()', 3000);
};
dashboard.show_success = function(id,str) {
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-success fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);	
};
dashboard.show_success_fix = function(id,str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-success fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);	
	dashboard._store.variable.timeout_alert = setTimeout('dashboard.time_out_close_alert()', 3000);
};
/**
 * Display loading gif
 * When waiting response from server
 * @param the id of div
 * Require a div which have same id in template
 */
dashboard.show_loading = function(id) {
	jQuery("#"+id).html("<div align='center'><img src='images/ajax-loading.gif' />&nbsp;Loading...</div>");
};

dashboard.time_out_close_alert = function(str) {
	$(".alert").alert('close');
}; 

dashboard.client_include = function(id, url){
	  var req = false;
	  // For Safari, Firefox, and other non-MS browsers
	  if (window.XMLHttpRequest) {
	    try {
	      req = new XMLHttpRequest();
	    } catch (e) {
	      req = false;
	    }
	  } else if (window.ActiveXObject) {
	    // For Internet Explorer on Windows
	    try {
	      req = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	      try {
	        req = new ActiveXObject("Microsoft.XMLHTTP");
	      } catch (e) {
	        req = false;
	      }
	    }
	  }
	 var element = document.getElementById(id);
	 if (!element) {
	  alert("Bad id " + id +
	   "passed to clientSideInclude." +
	   "You need a div or span element " +
	   "with this id in your page.");
	  return;
	 }
	  if (req) {
	    // Synchronous request, wait till we have it all
	    req.open('GET', url, false);
	    req.send(null);
	    element.innerHTML = req.responseText;
	  } else {
	    element.innerHTML =
	   "Sorry, your browser does not support " +
	      "XMLHTTPRequest objects. This page requires " +
	      "Internet Explorer 5 or better for Windows, " +
	      "or Firefox for any system, or Safari. Other " +
	      "compatible browsers may also exist.";
	  }
}

dashboard.generate_path = function(arrParams){
	var path = BASE_URL;
	for (var i = 0; i < arrParams.length; i++) {
		if (i < (arrParams.length - 1)) {
			path += arrParams[i] + "/";
		} else {
			path += arrParams[i] + "?rnd=" + Math.random();
		}
	}
	return path;
}
dashboard.util_date = {
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
	getDateFromFormat : function (val,format) {
		val=val+"";
		format=format+"";
		var i_val=0;
		var i_format=0;
		var c="";
		var token="";
		var token2="";
		var x,y;
		var now=new Date();
		var year=now.getYear();
		var month=now.getMonth()+1;
		var date=1;
		var hh=now.getHours();
		var mm=now.getMinutes();
		var ss=now.getSeconds();
		var ampm="";
		
		while (i_format < format.length) {
			// Get next token from format string
			c=format.charAt(i_format);
			token="";
			while ((format.charAt(i_format)==c) && (i_format < format.length)) {
				token += format.charAt(i_format++);
				}
			// Extract contents of value based on format token
			if (token=="yyyy" || token=="yy" || token=="y") {
				if (token=="yyyy") { x=4;y=4; }
				if (token=="yy")   { x=2;y=2; }
				if (token=="y")    { x=2;y=4; }
				year=_getInt(val,i_val,x,y);
				if (year==null) { return 0; }
				i_val += year.length;
				if (year.length==2) {
					if (year > 70) { year=1900+(year-0); }
					else { year=2000+(year-0); }
					}
				}
			else if (token=="MMM"||token=="NNN"){
				month=0;
				for (var i=0; i<MONTH_NAMES.length; i++) {
					var month_name=MONTH_NAMES[i];
					if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
						if (token=="MMM"||(token=="NNN"&&i>11)) {
							month=i+1;
							if (month>12) { month -= 12; }
							i_val += month_name.length;
							break;
							}
						}
					}
				if ((month < 1)||(month>12)){return 0;}
				}
			else if (token=="EE"||token=="E"){
				for (var i=0; i<DAY_NAMES.length; i++) {
					var day_name=DAY_NAMES[i];
					if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
						i_val += day_name.length;
						break;
						}
					}
				}
			else if (token=="MM"||token=="M") {
				month=_getInt(val,i_val,token.length,2);
				if(month==null||(month<1)||(month>12)){return 0;}
				i_val+=month.length;}
			else if (token=="dd"||token=="d") {
				date=_getInt(val,i_val,token.length,2);
				if(date==null||(date<1)||(date>31)){return 0;}
				i_val+=date.length;}
			else if (token=="hh"||token=="h") {
				hh=_getInt(val,i_val,token.length,2);
				if(hh==null||(hh<1)||(hh>12)){return 0;}
				i_val+=hh.length;}
			else if (token=="HH"||token=="H") {
				hh=_getInt(val,i_val,token.length,2);
				if(hh==null||(hh<0)||(hh>23)){return 0;}
				i_val+=hh.length;}
			else if (token=="KK"||token=="K") {
				hh=_getInt(val,i_val,token.length,2);
				if(hh==null||(hh<0)||(hh>11)){return 0;}
				i_val+=hh.length;}
			else if (token=="kk"||token=="k") {
				hh=_getInt(val,i_val,token.length,2);
				if(hh==null||(hh<1)||(hh>24)){return 0;}
				i_val+=hh.length;hh--;}
			else if (token=="mm"||token=="m") {
				mm=_getInt(val,i_val,token.length,2);
				if(mm==null||(mm<0)||(mm>59)){return 0;}
				i_val+=mm.length;}
			else if (token=="ss"||token=="s") {
				ss=_getInt(val,i_val,token.length,2);
				if(ss==null||(ss<0)||(ss>59)){return 0;}
				i_val+=ss.length;}
			else if (token=="a") {
				if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
				else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
				else {return 0;}
				i_val+=2;}
			else {
				if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
				else {i_val+=token.length;}
				}
			}
		// If there are any trailing characters left in the value, it doesn't match
		if (i_val != val.length) { return 0; }
		// Is date valid for month?
		if (month==2) {
			// Check for leap year
			if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
				if (date > 29){ return 0; }
				}
			else { if (date > 28) { return 0; } }
			}
		if ((month==4)||(month==6)||(month==9)||(month==11)) {
			if (date > 30) { return 0; }
			}
		// Correct hours value
		if (hh<12 && ampm=="PM") { hh=hh-0+12; }
		else if (hh>11 && ampm=="AM") { hh-=12; }
		var newdate=new Date(year,month-1,date,hh,mm,ss);
		return newdate.getTime();
	},
	// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
	formatDate :function (date,format) {
		format=format+"";
		var result="";
		var i_format=0;
		var c="";
		var token="";
		var y=date.getYear()+"";
		var M=date.getMonth()+1;
		var d=date.getDate();
		var E=date.getDay();
		var H=date.getHours();
		var m=date.getMinutes();
		var s=date.getSeconds();
		var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
		// Convert real date parts into formatted versions
		var value=new Object();
		if (y.length < 4) {y=""+(y-0+1900);}
		value["y"]=""+y;
		value["yyyy"]=y;
		value["yy"]=y.substring(2,4);
		value["M"]=M;
		value["MM"]=LZ(M);
		value["MMM"]=MONTH_NAMES[M-1];
		value["NNN"]=MONTH_NAMES[M+11];
		value["d"]=d;
		value["dd"]=LZ(d);
		value["E"]=DAY_NAMES[E+7];
		value["EE"]=DAY_NAMES[E];
		value["H"]=H;
		value["HH"]=LZ(H);
		if (H==0){value["h"]=12;}
		else if (H>12){value["h"]=H-12;}
		else {value["h"]=H;}
		value["hh"]=LZ(value["h"]);
		if (H>11){value["K"]=H-12;} else {value["K"]=H;}
		value["k"]=H+1;
		value["KK"]=LZ(value["K"]);
		value["kk"]=LZ(value["k"]);
		if (H > 11) { value["a"]="PM"; }
		else { value["a"]="AM"; }
		value["m"]=m;
		value["mm"]=LZ(m);
		value["s"]=s;
		value["ss"]=LZ(s);
		while (i_format < format.length) {
			c=format.charAt(i_format);
			token="";
			while ((format.charAt(i_format)==c) && (i_format < format.length)) {
				token += format.charAt(i_format++);
				}
			if (value[token] != null) { result=result + value[token]; }
			else { result=result + token; }
			}
		return result;
	},	
	// initDataSelectMonth : function (selectID) {
			// jQuery("select#" + selectID).append("<option value='0'>Month&nbsp;</option>");
			// var m_names = new Array("Jan", "Feb", "Mar", 
									// "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
									// "Oct", "Nov", "Dec");
			// for (var i = 0; i < m_names.length; i++) {
				// jQuery("select#" + selectID).append("<option value='" + (i+1) + "'>" + m_names[i] + "&nbsp;</option>");
			// }
		// },
	

	// initDataSelectDay : function (selectID, maxDay) {
		// jQuery("select#" + selectID).children().remove();
		// jQuery("select#" + selectID).append("<option value='0'>Day&nbsp;</option>");
		// var value = "";
		// for (var i = 1; i <= maxDay; i++) {
			// value = (i < 10) ? "0" + i : i;
			// jQuery("select#" + selectID).append("<option value='" + i + "'>" + value + "&nbsp;</option>");
		// }
	// },
	// initDataSelectYear : function (selectID) {
		// jQuery("select#" + selectID).append("<option value='0'>Year&nbsp;</option>");
		// var currDateTime = new Date();
		// var year = currDateTime.getFullYear()
		// for (var i = 0; i < 150; i++) {
			// jQuery("select#" + selectID).append("<option value='" + year + "'>" + year + "&nbsp;</option>");
			// year -= 1;
		// }
	// },
	initDataSelectMonth : function (selectID) {
		jQuery("ul#" + selectID).append("<li rel='0'><a href='#'>Month</a></li>");
		var m_names = new Array("Jan", "Feb", "Mar", 
								"Apr", "May", "Jun", "Jul", "Aug", "Sep", 
								"Oct", "Nov", "Dec");
		for (var i = 0; i < m_names.length; i++) {
			jQuery("ul#" + selectID).append("<li rel='" + (i+1) + "'><a href='#'>" + m_names[i] + "</a></li>");
		}
	},
	initDataSelectDay : function (selectID, maxDay) {
		jQuery("ul#" + selectID).children().remove();
		jQuery("ul#" + selectID).append("<li rel='0'><a href='#'>Day</a></li>");
		var value = "";
		for (var i = 1; i <= maxDay; i++) {
			value = (i < 10) ? "0" + i : i;
			jQuery("ul#" + selectID).append("<li rel='" + i + "'><a href='#'>" + value + "</a></li>");
		}
	},
	
	initDataSelectYear : function (selectID) {
		jQuery("ul#" + selectID).append("<li rel='0'><a href='#'>Year</a></li>");
		var currDateTime = new Date();
		var year = currDateTime.getFullYear()
		for (var i = 0; i < 150; i++) {
			jQuery("ul#" + selectID).append("<li rel='" + year + "'><a href='#'>" + year + "</a></li>");
			year -= 1;
		}
	},

	validateDate : function (slctMonth, slctDay, slctYear) {
		var month = jQuery("#" + slctMonth ).attr("tabindex");
		var day = jQuery("#" + slctDay ).attr("tabindex");
		var year = jQuery("#" + slctYear ).attr("tabindex");
		// console.log(month +"-"+ day + "-" + year);
		if (month == 0) {
			dashboard.util_date.resetSelectDay(slctDay, day, 31);
		} else if ((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12)) {
			dashboard.util_date.resetSelectDay(slctDay, day, 31);
		} else if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
			dashboard.util_date.resetSelectDay(slctDay, day, 30);
		} else if (month == 2) {
			if (year == 0) {
				dashboard.util_date.resetSelectDay(slctDay, day, 29);
			} else {
				if (dashboard.util_date.isLeapYear(year)) {
					dashboard.util_date.resetSelectDay(slctDay, day, 29);
				} else {
					dashboard.util_date.resetSelectDay(slctDay, day, 28);
				}
			}
		}
	},

	resetSelectDay : function (slctDay, day, maxDay) {
		var dayOfMonth = (day > maxDay) ? 0 : day;
		var b = (parseInt(dayOfMonth) == 0 ? "Day" : dayOfMonth);		
			b += dashboard.join(' <span class="caret"></span>')();		
		$("#"+slctDay).attr("tabindex", dayOfMonth).html(b);	
		// console.log(b+slctDay);	
		var c = $("#"+slctDay).next("ul").attr("id");
		// console.log(c);
		// console.log(day);
		dashboard.util_date.initDataSelectDay( c , maxDay);	
		//update function for select day 
		//because jquery remove function click for select day
		//and then we enable it
		dashboard.carecoach.firstPrepareToSearch(c,slctDay);		
	},

	isLeapYear : function (yr) {
	    //Every year divisible by 4 is a leap year.
	    //But every year divisible by 100 is NOT a leap year
	    //Unless the year is also divisible by 400, then it is still a leap year.
	
		if ((parseInt(yr) % 4) == 0) {
	  		if (parseInt(yr) % 100 == 0) {
	    		if (parseInt(yr) % 400 != 0) {
	    			//Not Leap
	    			return false;
	    		} else {
		    		//Leap
		    		return true;
		    	}
	  		} else {
		    	//Leap
		    	return true;
		  	}
	 	} else {
	    	//Not Leap
	    	return false;
	 	}
	}
}


var LoadingScreen = {
	start : function() {
		var self = this;		
		if(!("webkitMask" in document.body.style)) {
			document.getElementById("loading_screen_background").style.backgroundImage = "none";
		}

		self._resize();
		if(dashboard.is_ie()){			
			window.attachEvent("onload", function() { LoadingScreen.stop(); });
		}else{					 
	  		window.addEventListener("resize", LoadingScreen._resize, false); 	  						
		}			
	},

	stop : function() {
		document.getElementById("loading_screen").style.display = "none";
	},

	_resize : function() {
		var window_height = $(window).height(); 		
		document.getElementById('loading_screen').style.height = window_height + "px";
		document.getElementById('loading_screen_logo').style.paddingTop = (window_height * .43) + "px";
	}
};
	  
var Utf8Encoder = {
 
    // URL utf-8 encoding
    encode : function (str) {
        return escape(this._utf8_encode(str));
    },
 
    // URL utf-8 decoding
    decode : function (encoded_str) {
        return this._utf8_decode(unescape(encoded_str));
    },
 
    // UTF-8 encoding
    _utf8_encode : function (str) {
        str = str.replace(/\r\n/g,"\n");
        var encoded_str = "";
 
        for (var n = 0; n < str.length; n++) {
 
            var c = str.charCodeAt(n);
 
            if (c < 128) {
                encoded_str += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                encoded_str += String.fromCharCode((c >> 6) | 192);
                encoded_str += String.fromCharCode((c & 63) | 128);
            }
            else {
                encoded_str += String.fromCharCode((c >> 12) | 224);
                encoded_str += String.fromCharCode(((c >> 6) & 63) | 128);
                encoded_str += String.fromCharCode((c & 63) | 128);
            }
        }
        return encoded_str;
    },
 
    // UTF-8 decoding
    _utf8_decode : function (encoded_str) {
        var str = "";
        var i = 0;
        var c = c1 = c2 = 0;
 
        while ( i < encoded_str.length ) {
 
            c = encoded_str.charCodeAt(i);
 
            if (c < 128) {
                str += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = encoded_str.charCodeAt(i+1);
                str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = encoded_str.charCodeAt(i+1);
                c3 = encoded_str.charCodeAt(i+2);
                str += String.fromCharCode(((c & 15) << 12) |
                                   ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return str;
    }
};
function BrowseServer( startupPath, functionData ){
	var finder = new CKFinder();
	finder.basePath = 'ckfinder/'; //Đường path nơi đặt ckfinder
	finder.startupPath = startupPath; //Đường path hiện sẵn cho user chọn file
	finder.selectActionFunction = SetFileField; // hàm sẽ được gọi khi 1 file được chọn
	finder.selectActionData = functionData; //id của text field cần hiện địa chỉ hình
	finder.selectThumbnailActionFunction = ShowThumbnails; //hàm sẽ được gọi khi 1 file thumnail được chọn
	finder.popup(); // Bật cửa sổ CKFinder
} //BrowseServer

function SetFileField( fileUrl, data ){
	document.getElementById( data["selectActionData"] ).value = fileUrl;
}
function ShowThumbnails( fileUrl, data ){
	var sFileName = this.getSelectedFile().name; // this = CKFinderAPI
	document.getElementById( 'thumbnails' ).innerHTML +=
	'<div class="thumb">' +
	'<img src="' + fileUrl + '" />' +
	'<div class="caption">' +
	'<a href="' + data["fileUrl"] + '" target="_blank">' + sFileName + '</a> (' + data["fileSize"] + 'KB)' +
	'</div>' +
	'</div>';
	document.getElementById( 'preview' ).style.display = "";
	return false; // nếu là true thì ckfinder sẽ tự đóng lại khi 1 file thumnail được chọn
}